# -*- coding: utf-8 -*-
import sys

sys.path.append('../..')
from common.config import *
from common.helper import Helper
from db.mysql import MysqlClient
from itertools import product
from pyquery import PyQuery as pq
import requests
from urllib.parse import urlencode
import json

class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "贴心保综合意外伤害保险"

    # 生成产品数据
    def genProductInfo(self):
        first, second, third, fourth = self.getProfessionInfo()
        plan = {

            "planA":{
                "days": ["1y"],
                "people_count": ["1"],
                "professions": [json.dumps(first, ensure_ascii=False)],
                "accident_death": ["200000", "300000"],
                "accident_disable": [str(i) for i in range(5, 25, 5)],
                "accident_medical": ["0", "1000", "3000", "5000", "10000", "15000", "20000"],
                "accident_hospital": ["0", "10/天", "20/天", "30/天", "40/天", "50/天"]
            },
            "planB":{
                "days": ["1y"],
                "people_count": ["1"],
                "professions": [json.dumps(second, ensure_ascii=False)],
                "accident_death": ["200000", "300000"],
                "accident_disable": [str(i) for i in range(5, 25, 5)],
                "accident_medical": ["0", "1000", "3000", "5000", "10000", "15000", "20000"],
                "accident_hospital": ["0", "10/天", "20/天", "30/天", "40/天", "50/天"]

            },
            "planC":{
                "days": ["1y"],
                "people_count": ["1"],
                "professions": [json.dumps(third, ensure_ascii=False)],
                "accident_death": ["200000", "300000"],
                "accident_disable": [str(i) for i in range(5, 25, 5)],
                "accident_medical": ["0", "1000", "3000", "5000", "10000", "15000", "20000"],
                "accident_hospital": ["0", "10/天", "20/天", "30/天", "40/天", "50/天"]

            },
            "planD":{
                "days": ["1y"],
                "people_count": ["1"],
                "professions": [json.dumps(fourth, ensure_ascii=False)],
                "accident_death": ["200000"],
                "accident_disable": [str(i) for i in range(5, 25, 5)],
                "accident_medical": ["0", "1000", "3000", "5000", "10000", "15000", "20000"],
                "accident_hospital": ["0", "10/天", "20/天", "30/天", "40/天", "50/天"]
            }

        }
        for k in plan:
            for v in product(plan[k]["days"], plan[k]["people_count"], plan[k]["professions"], plan[k]["accident_death"],
                             plan[k]["accident_disable"], plan[k]["accident_medical"], plan[k]["accident_hospital"]):
                data = {
                    "days": v[0],
                    "people_count": v[1],
                    "professions": "'" + v[2] + "'",
                    "accident_death": v[3],
                    "accident_disable": v[4],
                    "accident_medical": v[5],
                    "accident_hospital": v[6]
                }
                self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(**data))
                self.mysql._conn.commit()
                print(domain[self.name]["insert_sql"].format(**data))

    # 执行爬虫
    def requestJson(self, dt=None, mysql=None):

        params = '''
        agentId: 
        sessionKey: myInsurance1b85abcb-9824-4e90-bbfe-96c67b1e165a
        pagePropertyObj.selectedPlanId: 2468
        pagePropertyObj.renewal: false
        pagePropertyObj.renewalCalendarStartDate: 
        pagePropertyObj.renewalCalendarEndDate: 
        source: 
        fuwu: 
        sso: true
        processId: buy-process-6e8024c4-3538-4fc6-942e-c6fca59593b2
        orderSource: product-center
        platform: pc
        statisticProductType: 01
        statisticProductId: 1712
        verifycode: 
        pagePropertyObj.pageProduct.ecInsurancplans[0].ecClauses[0].clauseId: 1650
        pagePropertyObj.pageProduct.ecInsurancplans[0].ecClauses[0].ecLiabilities[0].liabilityId: 1864
        pagePropertyObj.pageProduct.ecInsurancplans[0].ecClauses[0].ecLiabilities[0].three: 
        pagePropertyObj.pageProduct.ecInsurancplans[0].ecClauses[0].ecLiabilities[0].isSelected: true
        pagePropertyObj.pageProduct.ecInsurancplans[0].ecClauses[0].ecLiabilities[0].amount: 20
        pagePropertyObj.pageProduct.ecInsurancplans[0].ecClauses[0].ecLiabilities[1].liabilityId: 1865
        pagePropertyObj.pageProduct.ecInsurancplans[0].ecClauses[0].ecLiabilities[1].three: 
        pagePropertyObj.pageProduct.ecInsurancplans[0].ecClauses[0].ecLiabilities[1].isSelected: true
        pagePropertyObj.pageProduct.ecInsurancplans[0].ecClauses[0].ecLiabilities[1].amount: 15
        pagePropertyObj.pageProduct.ecInsurancplans[0].ecClauses[1].clauseId: 1653
        pagePropertyObj.pageProduct.ecInsurancplans[0].ecClauses[1].ecLiabilities[0].liabilityId: 1866
        pagePropertyObj.pageProduct.ecInsurancplans[0].ecClauses[1].ecLiabilities[0].three: 
        pagePropertyObj.pageProduct.ecInsurancplans[0].ecClauses[1].ecLiabilities[0].amount: 0
        pagePropertyObj.pageProduct.ecInsurancplans[0].ecClauses[2].clauseId: 1654
        pagePropertyObj.pageProduct.ecInsurancplans[0].ecClauses[2].ecLiabilities[0].liabilityId: 1867
        pagePropertyObj.pageProduct.ecInsurancplans[0].ecClauses[2].ecLiabilities[0].three: 1
        pagePropertyObj.pageProduct.ecInsurancplans[0].ecClauses[2].ecLiabilities[0].amount: 0
        pagePropertyObj.occupationLevel: 4
        pagePropertyObj.occupationCode: 0816007
        pagePropertyObj.occupationName: 家用空调安装与维修
        pagePropertyObj.insuStartDate: 2020-04-27
        pagePropertyObj.insuPeriod: 1
        pagePropertyObj.insuPeriodUnit: 03
        pagePropertyObj.insuEndDate: 2021-04-26
        '''
        data = Helper.perfectJson(params)
        data["pagePropertyObj.pageProduct.ecInsurancplans[0].ecClauses[0].ecLiabilities[0].amount"] = str(int(int(dt["accident_death"])/10000))
        data["pagePropertyObj.pageProduct.ecInsurancplans[0].ecClauses[0].ecLiabilities[1].amount"] = dt["accident_disable"]
        data["pagePropertyObj.pageProduct.ecInsurancplans[0].ecClauses[1].ecLiabilities[0].amount"] = "0" if dt["accident_medical"] == "0" else float(int(dt["accident_medical"])/10000)
        data["pagePropertyObj.pageProduct.ecInsurancplans[0].ecClauses[2].ecLiabilities[0].amount"] = "0" if dt["accident_hospital"] == "0" else dt["accident_hospital"].replace("/天","")

        # 判断职业等级
        if  "铁路票房工作人员" in dt["professions"]:
            data["pagePropertyObj.occupationLevel"] = "1"
            data["pagePropertyObj.occupationName"]  = "铁路票房工作人员"
            data["pagePropertyObj.occupationCode"] = "0502002"
        elif "公路收费及监控人员" in dt["professions"]:
            data["pagePropertyObj.occupationLevel"] = "2"
            data["pagePropertyObj.occupationName"] = "公路收费及监控人员"
            data["pagePropertyObj.occupationCode"] = "0501023"
        elif "自来水管装修人员" in dt["professions"]:
            data["pagePropertyObj.occupationLevel"] = "3"
            data["pagePropertyObj.occupationName"] = "自来水管装修人员"
            data["pagePropertyObj.occupationCode"] = "1403004"
        else:
            data["pagePropertyObj.occupationLevel"] = "4"
            data["pagePropertyObj.occupationName"] = "家用空调安装与维修"
            data["pagePropertyObj.occupationCode"] = "0816007"

        payload = urlencode(data).replace("+", "")
        r = requests.post(url=domain[self.name]["url"], headers=domain[self.name]["header"], data=payload)

        if r.status_code == 200 and "premium" in r.text:
            prices = [price["premium"] for price in r.json()["pagePropertyObj"]["liabilityList"]]
            price = Helper.decimalParse(sum(prices))
            data = {
                "name":self.name,
                "id":dt["id"],
                "price":price
            }
            print( data )
            mysql.updatePrice( data )
        else:
            data = {
                "name":self.name,
                "id":dt["id"],
                "state":3
            }
            mysql.updateTask( data )
            print("\n/*更新产品价格失败:%d*/"%dt["id"])

    # 获取职业信息
    def getProfessionInfo(self):
        jb_url = "https://product.sinosig.com/quote_quote.action?id=1712&insuredBuyNum=1&agentId=&source=&fuwu=&processId=buy-process-6e8024c4-3538-4fc6-942e-c6fca59593b2&orderSource=product-center&platform=pc&statisticProductType=&statisticProductId=1712"
        action_url = "https://product.sinosig.com/quote_getOccupationpsByFatherId.action"
        doc = pq(jb_url)
        items = doc(".scroll_div ul li ").items()
        headers = headers_raw_to_dict(
            b'''
            Accept: application/json, text/javascript, */*
            Accept-Encoding: gzip, deflate, br
            Accept-Language: zh-CN,zh;q=0.9
            Connection: keep-alive
            Content-Length: 11
            Content-Type: application/x-www-form-urlencoded
            Host: product.sinosig.com
            Origin: https://product.sinosig.com
            Referer: https://product.sinosig.com/quote_quote.action?id=1712&insuredBuyNum=1&agentId=&source=&fuwu=&processId=buy-process-6e8024c4-3538-4fc6-942e-c6fca59593b2&orderSource=product-center&platform=pc&statisticProductType=&statisticProductId=1712
            Sec-Fetch-Dest: empty
            Sec-Fetch-Mode: cors
            Sec-Fetch-Site: same-origin
            User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.113 Safari/537.36
            X-Requested-With: XMLHttpRequest
            '''
        )
        first_level = []
        second_level = []
        third_level = []
        fourth_level = []
        for item in items:
            data = {
                "id": item("input").attr("id"),
                "name": item.text()
            }
            g = lambda: requests.post(url=action_url, headers=headers, data="fatherId=" + data["id"] + "").json()

            for g in g():

                c = lambda: requests.post(url=action_url, headers=headers, data="fatherId=" + g["code"] + "").json()

                for c in c():

                    if c["rickLevel"] == "1":
                        first_level.append(c["name"])
                    elif c["rickLevel"] == "2":
                        second_level.append(c["name"])
                    elif c["rickLevel"] == "3":
                        third_level.append(c["name"])
                    elif c["rickLevel"] == "4":
                        fourth_level.append(c["name"])
                    else:
                        pass
        return  (first_level, second_level, third_level, fourth_level)

